import copy
from rest_framework.views import APIView
from rest_framework_simplejwt.tokens import AccessToken
from CloudGuardian.models import BindRelationship
from SecureHelperServer.settings import formatResponseData
from User.models import User, EmailVerificationRecord
from utils.conf import newID, newUserName, newBindCode, Response
from utils.loggingConfig import logger


class CheckVerificationCodeView(APIView):
    # 局部(本视图有效)身份认证
    authentication_classes = []
    # 局部(本视图有效)权限认证
    permission_classes = []

    def post(self, request, *args, **kwargs):
        """
        验证验证码
        """
        data = copy.deepcopy(formatResponseData)
        try:
            emailVerificationRecordId = request.data.get("emailVerificationRecordId")
            verificationCode = request.data.get("verificationCode")
            selectLoginType = request.data.get("selectLoginType")

            if not (emailVerificationRecordId and verificationCode and selectLoginType):
                return Response(data=data, responseMsg="请求参数缺失", loggerMsg="请求参数缺失", isError=True)

            # 查询验证记录
            emailVerificationRecord = EmailVerificationRecord.objects.filter(id=emailVerificationRecordId).first()
            if not emailVerificationRecord and emailVerificationRecord.isValid:
                return Response(data=data, responseMsg="验证码已过期",
                                loggerMsg=f"验证验证码：验证码已过期: emailVerificationRecordId={emailVerificationRecordId}",
                                isError=True)

            # 校验登录信息
            if not emailVerificationRecord.verificationCode == verificationCode:
            # if not verificationCode == '262343':
                return Response(data=data, responseMsg="验证码错误",
                                loggerMsg=f"验证验证码：验证码错误: emailVerificationRecordId={emailVerificationRecordId}",
                                isError=True)

            user = User.objects.filter(email=emailVerificationRecord.email).first()
            # 新用户
            if not user:
                uid = newID()
            # 老用户
            else:
                uid = user.uid

            user, isNewUser = User.objects.get_or_create(uid=uid, email=emailVerificationRecord.email)
            if isNewUser:
                user.username = newUserName()
                user.bindCode = newBindCode()
                user.save()
                logger.info(f"创建了新用户：user={user.uid}")

            # 可供选择登录的所有用户
            userList = []

            # 通过自己的邮箱登录
            if selectLoginType == "loginBySelfEmail":
                userList.append(user)

            # 如果是通过监护人邮箱进行登录
            elif selectLoginType == "loginByGuardianEmail":
                # 找出该监护人绑定过的所有对象
                userList.extend([bindRelationship.wardUser for bindRelationship in
                                 BindRelationship.objects.filter(guardianUser=user)])

            """
            手动签发 JWT Token
            """
            userInfoList = []
            for user in userList:
                tokenObj = AccessToken.for_user(user)
                token = str(tokenObj)
                userInfoList.append({
                    'username': user.username,
                    'token': token,
                })

            data["data"]["userInfoList"] = userInfoList
            return Response(data=data, responseMsg="验证成功",
                            loggerMsg=f"验证验证码: 成功，email={emailVerificationRecord.email}")

        except Exception as e:
            return Response(data=data, responseMsg="ServerError",
                            loggerMsg=f"请求处理失败: {e}", isError=True)
